import { ref } from "vue";
import { defineStore } from "pinia";
import { loginApi, getUserInfoApi } from "@/api/user";

export const useUserStore = defineStore("user", () => {
  // 1. 当前store需要管理什么数据
  const user = uni.getStorageSync("user");

  const token = ref(uni.getStorageSync("token") || "");
  const nickname = ref(user.nickname || "");
  const avatar = ref(user.avatar || "");
  const hasLogin = ref(user.nickname ? true : false);

  // 2. 定义actions
  const login = async (code: string) => {
    const res = await loginApi(code);
    token.value = res.token;
    uni.setStorageSync("token", token.value);

    await getUserInfo();
  };

  const getUserInfo = async () => {
    const { item } = await getUserInfoApi();
    nickname.value = item.nickname;
    avatar.value = item.avatar;
    hasLogin.value = true;
    uni.setStorageSync("user", {
      nickname: nickname.value,
      avatar: avatar.value,
    });
  };

  return {
    token,
    nickname,
    avatar,
    hasLogin,
    login,
    getUserInfo,
  };
});

// export const useUserStore = defineStore("user", {
//   state() {
//     return {};
//   },
//   getters: {},
//   actions: {},
// });
